#include "login_widget.h"
#include "ui_login_widget.h"
#include <QMouseEvent>
#include <QDebug>
#include <QIcon>
#include <QFile>
#include <QTextStream>
#include "panel_main_window.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include "database_manager.h"
#include "dealer_handler.h"
#include <QJsonObject>
#include <QJsonDocument>

LoginWidget::LoginWidget(QWidget *parent)
    : QWidget(parent),
      ui_(new Ui::LoginWidget),
      is_dragging_(false),
      main_window_(nullptr),
      dealer_handler_(nullptr)
{
    ui_->setupUi(this);
    // 设置窗口无边框
    setWindowFlags(Qt::FramelessWindowHint);

    // 加载通用样式
    QFile commonStyleFile(":/styles/styles.qss");
    if (commonStyleFile.open(QFile::ReadOnly | QFile::Text))
    {
        QTextStream in(&commonStyleFile);
        in.setCodec("UTF-8");
        QString style = in.readAll();
        this->setStyleSheet(style);
        commonStyleFile.close();
    }

    connect(ui_->loginButton, &QPushButton::clicked, this, &LoginWidget::onLoginButtonClicked);
    connect(ui_->closeButton, &QPushButton::clicked, this, &QWidget::close);
    connect(ui_->configButton, &QPushButton::clicked, this, &LoginWidget::onConfigButtonClicked);
    connect(ui_->saveButton, &QPushButton::clicked, this, &LoginWidget::onSaveButtonClicked);
    connect(ui_->showPasswordButton, &QPushButton::clicked, this, &LoginWidget::onShowPasswordButtonClicked);

    // 安装事件过滤器
    ui_->usernameEdit->installEventFilter(this);
    ui_->passwordEdit->installEventFilter(this);

    // 设置用户名输入框获得焦点
    ui_->usernameEdit->setFocus();

    // 初始化数据库
    if (!DatabaseManager::initialize())
    {
        exit(-1);
    }
}

LoginWidget::~LoginWidget()
{
    delete ui_;
    delete main_window_;
    DatabaseManager::close();
    if (dealer_handler_)
    {
        dealer_handler_->stop();
    }
}

void LoginWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        drag_position_ = event->globalPos() - frameGeometry().topLeft();
        is_dragging_ = true;
    }
}

void LoginWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (is_dragging_)
    {
        move(event->globalPos() - drag_position_);
    }
}

void LoginWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        is_dragging_ = false;
    }
}

void LoginWidget::onLoginButtonClicked()
{
    // 初始化网络
    initNetwork();

    QString username = ui_->usernameEdit->text();
    QString password = ui_->passwordEdit->text();
    // 请求登录
    QJsonObject json;
    json["username"] = username;
    json["password"] = password;
    dealer_handler_->sendRequest("login", QJsonDocument(json).toJson(QJsonDocument::Compact));
}

void LoginWidget::onConfigButtonClicked()
{
    int index = ui_->stackedWidget->currentIndex();
    if (index == 1)
    {
        ui_->stackedWidget->setCurrentIndex(0);
    }
    else
    {
        // 查询并回显配置
        QSqlQuery query(DatabaseManager::getInstance());
        QStringList keys = {"server_ip", "server_port", "machine_code"};
        QMap<QString, QString> configMap;

        for (const QString &key : keys)
        {
            query.prepare("SELECT config_val FROM config WHERE config_key = ?");
            query.addBindValue(key);
            if (query.exec() && query.next())
            {
                configMap[key] = query.value(0).toString();
            }
        }

        // 回显到输入框
        ui_->ipEdit->setText(configMap.value("server_ip", ""));
        ui_->portEdit->setText(configMap.value("server_port", ""));
        ui_->machineCodeEdit->setText(configMap.value("machine_code", ""));

        ui_->stackedWidget->setCurrentIndex(1);
    }
}

void LoginWidget::onSaveButtonClicked()
{
    QString ip_edit = ui_->ipEdit->text();
    QString port_edit = ui_->portEdit->text();
    QString machine_code_edit = ui_->machineCodeEdit->text();

    // 验证IP地址格式
    QRegExp ipRegex("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    if (!ipRegex.exactMatch(ip_edit))
    {
        QMessageBox::warning(this, "错误", "IP地址格式不正确");
        ui_->ipEdit->clear();
        ui_->ipEdit->setFocus();
        return;
    }

    // 验证端口号
    bool ok;
    int port = port_edit.toInt(&ok);
    if (!ok || port < 1 || port > 65535)
    {
        QMessageBox::warning(this, "错误", "端口号必须在1-65535之间");
        ui_->portEdit->clear();
        ui_->portEdit->setFocus();
        return;
    }

    QSqlQuery query(DatabaseManager::getInstance());

    // 开启事务
    DatabaseManager::getInstance().transaction();

    // 检查并更新/插入配置
    QStringList keys = {"server_ip", "server_port", "machine_code"};
    QStringList values = {ip_edit, port_edit, machine_code_edit};

    for (int i = 0; i < keys.size(); ++i)
    {
        query.prepare("SELECT id FROM config WHERE config_key = ?");
        query.addBindValue(keys[i]);
        if (!query.exec())
        {
            qDebug() << "Query error:" << query.lastError().text();
            DatabaseManager::getInstance().rollback();
            return;
        }

        if (query.next())
        {
            // 更新已存在的配置
            query.prepare("UPDATE config SET config_val = ? WHERE config_key = ?");
            query.addBindValue(values[i]);
            query.addBindValue(keys[i]);
        }
        else
        {
            // 插入新配置
            query.prepare("INSERT INTO config (config_key, config_val) VALUES (?, ?)");
            query.addBindValue(keys[i]);
            query.addBindValue(values[i]);
        }

        if (!query.exec())
        {
            qDebug() << "Update/Insert error:" << query.lastError().text();
            DatabaseManager::getInstance().rollback();
            return;
        }
    }

    // 提交事务
    if (!DatabaseManager::getInstance().commit())
    {
        qDebug() << "Commit error:" << DatabaseManager::getInstance().lastError().text();
        DatabaseManager::getInstance().rollback();
        return;
    }

    QMessageBox::information(this, "成功", "配置保存成功");
    ui_->stackedWidget->setCurrentIndex(0);
}

bool LoginWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)
        {
            if (obj == ui_->usernameEdit)
            {
                // 用户名输入框按回车，切换到密码输入框
                ui_->passwordEdit->setFocus();
                return true;
            }
            else if (obj == ui_->passwordEdit)
            {
                // 密码输入框按回车，触发登录
                onLoginButtonClicked();
                return true;
            }
        }
    }
    return QWidget::eventFilter(obj, event);
}

/**
 * @brief 初始化网络
 */
void LoginWidget::initNetwork()
{
    if (dealer_handler_ == nullptr)
    {
        dealer_handler_ = DealerHandler::getInstance();
        // 从数据库读取配置
        QSqlQuery query(DatabaseManager::getInstance());
        QStringList keys = {"server_ip", "server_port"};
        QMap<QString, QString> configMap;

        for (const QString &key : keys)
        {
            query.prepare("SELECT config_val FROM config WHERE config_key = ?");
            query.addBindValue(key);
            if (query.exec() && query.next())
            {
                configMap[key] = query.value(0).toString();
            }
        }

        QString server_ip = configMap.value("server_ip", "127.0.0.1");
        QString server_port = configMap.value("server_port", "10002");

        // 初始化网络连接
        QString endpoint = QString("tcp://%1:%2").arg(server_ip).arg(server_port);
        dealer_handler_->initialize(endpoint);

        // 连接网络消息接收
        connect(dealer_handler_, &DealerHandler::messageReceived, this, &LoginWidget::onNetworkMessageReceived);
    }
}

void LoginWidget::onNetworkMessageReceived(const QString &method, const QString &body, bool is_error)
{
    if (is_error)
    {
        QMessageBox::warning(this, "错误", "网络无法连接");
        return;
    }

    if (method == "login")
    {
        if (body == "success")
        {
            // 断开信号连接
            disconnect(dealer_handler_, &DealerHandler::messageReceived, this, &LoginWidget::onNetworkMessageReceived);
            
            // 登录成功
            this->close();
            main_window_ = new PanelMainWindow();
            main_window_->setWindowTitle("控制指令监测分析系统");
            main_window_->showMaximized();
        }
        else
        {
            // 登录失败
            QMessageBox::warning(this, "错误", "用户名或密码错误");
        }
    }
}

void LoginWidget::onShowPasswordButtonClicked()
{
    if (ui_->passwordEdit->echoMode() == QLineEdit::Password)
    {
        ui_->passwordEdit->setEchoMode(QLineEdit::Normal);
        ui_->showPasswordButton->setIcon(QIcon(":/icons/svg/eye-slash-white.svg"));
    }
    else
    {
        ui_->passwordEdit->setEchoMode(QLineEdit::Password);
        ui_->showPasswordButton->setIcon(QIcon(":/icons/svg/eye-white.svg"));
    }
}
